function [ConfusionMatrix, TP, FN, FP, TN] = Ddavid_get_confusion_matrix(TrueLabel, SampledTrueLabel, PreLabel)

% [ConfusionMatrix, TP, FN, FP, TN] = Ddavid_get_confusion_matrix(TrueLabel, PreLabel)
%
% <Input>
% TrueLabel: [n*m], the value is {1, -1}, the true labels of all
%            instances
% SampledTrueLabel: [n*m], the value is {1, -1}, the sampled labels of all
%                   instances
% PreLabel: [n*m], the value is {1, -1}, the predict labels of all
%           instances
%
% <Output>
% ConfusionMatrix: [10*m], the confusion matrices of all labels, where
%                  the order is [TrueLabelSize SampledLabelSize PreLabelSize TP FN FP TN CorrectRecover WrongRecover Missing]
% TP, FN, FP, TN: Total TP, FN, FP and TN of all labels

N = size(TrueLabel, 1);
M = size(TrueLabel, 2);
TotalSize = N * M;
ConfusionMatrix = zeros(10, M);
TP = 0;
FN = 0;
FP = 0;
TN = 0;

ConfusionMatrix(1, :) = sum(TrueLabel == 1, 1);
ConfusionMatrix(2, :) = sum(SampledTrueLabel == 1, 1);
ConfusionMatrix(3, :) = sum(PreLabel == 1, 1);

for i = 1:M
    TempConfusionMatrix = confusionmat(TrueLabel(:, i), PreLabel(:, i), 'order', [1 -1])';
    ConfusionMatrix(4:7, i) = TempConfusionMatrix(:);

    TP = TP + ConfusionMatrix(4, i);
    FN = FN + ConfusionMatrix(5, i);
    FP = FP + ConfusionMatrix(6, i);
    TN = TN + ConfusionMatrix(7, i);
end

ConfusionMatrix(8, :) = sum((TrueLabel == 1) & (SampledTrueLabel == -1) & (PreLabel == 1), 1);
ConfusionMatrix(9, :) = sum((TrueLabel == -1) & (SampledTrueLabel == -1) & (PreLabel == 1), 1);
ConfusionMatrix(10, :) = sum((TrueLabel == 1) & (SampledTrueLabel == 1) & (PreLabel == -1), 1);

TP = TP / TotalSize;
FN = FN / TotalSize;
FP = FP / TotalSize;
TN = TN / TotalSize;
